﻿using filecopy.io.Container;
using System;

namespace filecopy.io.Item
{
    public class FsItem : IFileCopyItem
    {
        internal string filepath { get; set; }
        internal FsContainer container { get; set; }
        public FsItem(IContainer container, string path)
        {
            this.filepath = path;
            if (container is FsContainer fsc) this.container = fsc;
            else throw new Exception("容器不匹配，当前填入非fs容器。");
        }
        public string FileName => System.IO.Path.GetFileName(filepath);

        public long ReadSize()
        {
            var info = new FileInfo(filepath);
            return info.Length;
        }
        public byte[] Buffer { get; internal set; } = Array.Empty<byte>();
        public IEnumerable<int> GetStream(int buffersize)
        {
            using (var stream = File.Open(filepath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                Buffer = new byte[buffersize];
                stream.Seek(0, SeekOrigin.Begin);
                var readed = 0;
                while ((readed = stream.Read(Buffer, 0, buffersize)) > 0)
                {
                    if (readed == 0) continue;
                    if (Buffer.Length > readed)
                    {
                        var newArray = new byte[readed];
                        Array.Copy(Buffer, 0, newArray, 0, readed-1);
                        Buffer = newArray;
                        yield return readed;
                        break;
                    }
                    yield return readed;
                }
                Buffer = Array.Empty<byte>();
            }
        }
    }
}
